package busuanzi.module;

import busuanzi.storage.RedisPool;
import busuanzi.util.Logs;
import com.alibaba.fastjson.JSON;
import com.google.common.base.Strings;
import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpResponseStatus;

import java.net.URL;
import java.util.Map;

import static busuanzi.util.Containers.newHashMap;
import static com.google.common.base.Strings.isNullOrEmpty;
import static sardine.Sardine.get;
import static sardine.Sardine.halt;

/**
 * Created by bruce on 15/12/4.
 */
public class Backs {

    public static void run() {
        //原方法保留
        get("/counter_beta", "application/json", (request, response) -> {

            String jsonpCallback = request.queryParams("jsonpCallback");
            if (isNullOrEmpty(jsonpCallback)) halt(HttpResponseStatus.BAD_REQUEST);

            String refer = request.headers(HttpHeaderNames.REFERER);
            if (isNullOrEmpty(refer)) halt(HttpResponseStatus.BAD_REQUEST);

            Logs.log("busuanzi v0 from: {}", refer);

            final URL referURL = new URL(refer);

            String referHost = referURL.getHost();
            String referPath = referURL.getPath();

            response.header(HttpHeaderNames.CONTENT_TYPE, "application/json");
            response.headerInt(HttpHeaderNames.EXPIRES, 0);

            return RedisPool.bath(jedis -> {

                double pageCounter, siteCounter = jedis.zincrby(referHost, 1.0, referHost);

                if (!(Strings.isNullOrEmpty(referPath) || "/".equals(referPath)))
                    pageCounter = jedis.zincrby(referHost, 1.0, referPath);
                else
                    pageCounter = siteCounter;

                Map values = newHashMap("site", siteCounter, "page", pageCounter, "version", 1);

                return String.format("try{%s(%s);}catch(e){}", jsonpCallback, JSON.toJSONString(values));
            });
        });
    }

}
